package com.xiaoran.robot.task;

import com.xiaoran.robot.entity.Plmm;
import com.xiaoran.robot.service.impl.PlmmServiceImpl;
import com.xiaoran.robot.utils.*;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

public class PlmmTask {
    private static final String API = "https://api.nmb.show/xiaojiejie";
    private static final String BasePath = YamlReader.instance.getValueByKey("mirai.plmmPath").toString();
    private static final String upYunPath = YamlReader.instance.getValueByKey("upyun.BaseUrl").toString();
    private final PlmmServiceImpl plmmService = SpringUtil.getBean(PlmmServiceImpl.class);

    public void task(){
        Thread t1 = new Thread(this::getPlmm, "t1");
        Thread t2 = new Thread(this::getPlmm, "t2");
        Thread t3 = new Thread(this::getPlmm, "t3");
        t1.start();
        t2.start();
        t3.start();
    }
    public void getPlmm() {
        List<Plmm> datalist = new ArrayList<>();
        for (int i = 0; i <= 200; i++) {
            String filePath = BasePath + new SimpleDateFormat("yyyyMMdd").format(new Date())
                    .concat("-").concat(UUID.randomUUID().toString()).concat(".jpg");
            String osFilePath = "plmm/" + new SimpleDateFormat("yyyyMMdd").format(new Date())
                    .concat("-").concat(UUID.randomUUID().toString()).concat(".jpg");
            Random random = new Random();
            int i1 = random.nextInt(2) + 1;
            File file = new File(filePath);
            System.out.println(filePath);
            boolean status = false;
            try {
                HttpConnectionUtils.trustEveryone();
                FileUtils.copyURLToFile(new URL(API + i1 + ".php"), file);
                UpYun upYun = new UpYun();
                System.out.println(osFilePath);
                status = upYun.writeFile(osFilePath, file, true);
            } catch (IOException | UpException e) {
//                e.printStackTrace();
                System.out.println("发生了某些错误");
            }
            if (status) {
                String savePath = upYunPath + osFilePath;
                datalist.add(new Plmm(null, savePath));
            }else{
                System.out.println("图片上传upyun失败");
            }
            if(i % 10 == 0) {
                System.out.println(Thread.currentThread().getName() + " -> " + i);
            }
        }
        plmmService.insertList(datalist);
    }
}
